package com.cunshe.service;

import com.cunshe.dao.EmailAddressDao;
import com.cunshe.domain.EmailAddress;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunkee.commons.utils.StringUtils;
import com.sunkee.entity.page.Pageable;
import com.sunkee.entity.page.Pageination;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class EmailAddressService {

    @Autowired
    private EmailAddressDao emailAddressDao;

    @Transactional(rollbackFor = Exception.class)
    public int insert(EmailAddress record) {
        EmailAddress emailAddress = get(record.getEmail());
        if(emailAddress != null){
            return 0;
        }
        record.setCreatetime(new Date());
        return emailAddressDao.insert(record);
    }

    public EmailAddress get(String email) {
        if(StringUtils.isBlank(email)){
            return null;
        }
        return emailAddressDao.list(EmailAddress.builder().email(email).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    public Pageable<EmailAddress> pagelist(int pageNo, int pageSize, String email) {
        Page<EmailAddress> page = PageHelper.startPage(pageNo, pageSize);
        List<EmailAddress> list = emailAddressDao.list(EmailAddress.builder().email(email).build());
        Pageination<EmailAddress> result = Pageination.of(pageNo, pageSize);
        result.setResult(list).setCount(page.getTotal());
        return result;
    }

    public List<EmailAddress> list(EmailAddress record) {
        return emailAddressDao.list(record);
    }

}